//
//  KKNetworkResponse.m
//  Questionnaire
//
//  Created by leo on 16/1/24.
//  Copyright © 2016年 leo. All rights reserved.
//

#import "KKNetworkResponse.h"

@implementation KKNetworkResponse

+ (instancetype)responseWithData:(NSData *)data request:(KKNetworkRequest *)request error:(NSString **)error {
    
    if (data != nil) {
        
        NSError *jsonError;
        NSDictionary *reslutDictionary = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &jsonError];
        
        if (reslutDictionary == nil && jsonError != nil) {
            *error = jsonError.description;
            return nil;
        }
        else {
            
            if (request.debug) {
                NSLog(@"response = %@", reslutDictionary);
            }
            
            NSInteger status = [reslutDictionary[@"status"] integerValue];
            if (status == 0) {
                *error = reslutDictionary[@"errMsg"];
                return nil;
            }
            else if(request.className != nil){
                Class class = NSClassFromString(request.className);
                
                NSArray *dataArray = reslutDictionary[@"result"];
                NSMutableArray *itemArray = [NSMutableArray array];
                
                for (NSDictionary *itemDictionary in dataArray) {
                    id object = [class new];
                    [object kk_parserJsonDictionary: itemDictionary];
                    [itemArray addObject: object];
                }
                
                KKNetworkResponse *response = [KKNetworkResponse new];
                response->_responseObject = itemArray;
                return response;
            }
            else {
                NSArray *dataArray = reslutDictionary[@"result"];
                KKNetworkResponse *response = [KKNetworkResponse new];
                response->_responseObject = dataArray;
                return response;
            }
        }
    }
    *error = @"数据类型错误";
    return nil;
}

@end
